<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/wolcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" class="input-with-select">
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="fn">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope>
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editDialogVisble"></el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete"></el-button>
            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button size="mini" type="warning" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 4, 8]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" :rules="addFormRules" @close="reset">

          <el-form :model="addForm"  ref="addForm" label-width="80px">
              <el-form-item label="用户名称" prop="username">
                <el-input v-model="addForm.username"></el-input>
              </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                  <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>

          <span slot="footer" class="dialog-footer">
             <el-button @click="addDialogVisible = false">取 消</el-button>
             <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
    </el-dialog>

    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%">

          <el-form :model="editForm" :rules="editFormRules"  ref="editRuleForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="用户名称">
                <el-input v-model="editForm.username" disabled></el-input>
              </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                  <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>

          <span slot="footer" class="dialog-footer">
             <el-button @click="editDialogVisible = false">取 消</el-button>
             <el-button type="primary" @click="subEdit">确 定</el-button>
          </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkEmail = (rule,v,cb)=>{
      var reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if(reg.test(v)){
        return cb()
      }
      cb(new Error('你输入的邮箱格式不正确'))
    }
     var checkMobile = (rule,v,cb)=>{
      var reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if(reg.test(v)){
        return cb()
      }
      cb(new Error('你输入的手机号码格式不正确'))
    }

    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      userList: [],
      addDialogVisible:false,
      editDialogVisible:false,
      addForm:{
        username: 'true',
        password: '123456',
        email:'123@123.com',
        mobile:'18911111111',
        },
        editForm:{
          
        },
       
        addFormRules:{
           username:[
             {required: true, message:'请输入用户名称', trigger:'blur'},
             {min:2, max:7, message: '用户名长度在2到7个字符', trigger: 'blur'}
           ],
           password:[
             {required: true, message:'请输入密码', trigger:'blur'},
             {min:5, max:10, message: '用户名长度在5到10个字符', trigger: 'blur'}
           ],
           email:[
             {required: true, message:'请输入邮箱', trigger:'blur'},
             { validator: checkEmail, trigger:'blur'}
           ],
           mobile:[
             {required: true, message:'请输入手机号码', trigger:'blur'},
             { validator: checkMobile, trigger:'blur'}
           ]
        
          
      }
    }
  },

  methods: {
    async getUserList() {
      var { data: res } = await this.axios.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status != 200) {
        return this.$message.error('服务器错误')
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    
    //  监听switch开关状态的改变
    async userStateChanged(userInfo) {
      console.log(userInfo)
      const { data: res } = await this.axios.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.srror('更新用户状态失败！')
      }
      this.$message.success('更新用户状态成功！')
    },
    handleSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    reset(){
      console.log(this)
      this.$refs.addForm.resetFields()
    },
     fn(){
          this.addDialogVisible=!this.addDialogVisible
        },
    addDialogVisibleClose(){
      this.$refs.addForm.resetFields()
    },
    addUser(){
         this.$refs.addForm.validate(async flag=>{
           if(flag){
             var {data:res} = await this.axios.post('users', this.addForm)
             console.log(res)
             if(res.meta.status == 201) {
               this.$message.success('创建成功了')
             }else{
               this.$message.success('创建失败了 可能是服务器的原因')
             }
             this.addDialogVisible= false
             this.getUserList()
           }
         })
    },
   
    async editUser(id){
      var {data:res}= await this.axios.get('users/'+id)
      if(res.meta.status ==200 ) {
        this.editForm = res.data
      }else{
        this.$message.error('服务器错误')
      }
      this.editDialogvisible= true
    },
     editDialogvisibleClose(){
      this.$refs.editRuleForm.resetFields()
    },
    subEdit(){
       this.$refs.editRuleForm.validate(async flag=>{
        if(flag) {
          console.log(this.editForm)
          var {data:res} = await this.axios.put('users/'+this.editForm.id,{
            email:this.editForm.email,
            mobile:this.editForm.mobile
          })
          console.log(res)
          if(res.mets.status==200) {
            this.$message.success('修改成功了')
          }else{
            this.$message.success('修改失败')
          }
          this.editDialogVisible = false
          this.getUserList()
        }
      })
      return
      this.editDialogVisible = !this.editDialogVisible
    },
    async delUser(){
      var result = await this.$confirm('此操作将永久删除该用户， 是否继续？','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err=>err)
      if(result=='confirm') {
        console.log('用户确认删除')
        var {data:res} = await this.axios.delete('users/'+id)
        if(res.meta.status == 200) {
          this.$message.success('删除用户成功')
          this.getUserList()
        }else{
          this.$message.success('服务器罢工了')
        }
      }else{
        this.$message.info('用户取消删除')
      }
    }
  },
  created() {
    this.getUserList()
  }
}
</script>

<style lang='css' scoped>
.el-breadcrumb {
  margin-bottom: 10px;
}
.el-table {
  margin-top: 10px;
}
</style>
